import { MobileOutlined, SearchOutlined, UserOutlined } from '@ant-design/icons'
import { useBoolean } from '@gnlab/utils/env-react'
import { Input } from 'antd'
import type { InputRef } from 'antd/es/input'
import { Actionable } from '@/desktop/components'
import { useSearchedContacts } from '@/desktop/logics/contacts-search'
import { useStreams } from '@/lib/utils'
import services from '@/services'
import { Permission } from '@/services/auth'
import type { ExternalItemTag, GroupTag } from '@/services/contact-types'
import type { Contact } from '@/services/contacts'
import { ContactType } from '@/services/contacts'
import Categories from './categories'
import {
  ChooseExternalTags,
  ChoosedExternalTags,
  ChooseGroupTags,
  ChoosedGroupTags,
} from './choose-tags'
import ContactList from './contact-list'
import { FullSearch } from './full-search'
import { HistorySearch } from './history-search'
import { MobileApply } from './mobile-apply/index'
import './index.module.less'

export function SearchModal(props: { initialType: ContactType; onClose: () => void }) {
  const { initialType, onClose } = props
  const [account, qywxs] = useStreams(services.auth.account$, services.qywxs.alives)
  const [type, setType] = useState(initialType)
  const [keyword, setKeyword] = useState('')
  const [externalTags, setExternalTags] = useState<ExternalItemTag[] | null>(null) // 客户标签搜索条件
  const [groupTags, setGroupTags] = useState<GroupTag[] | null>(null) // 群标签搜索条件

  const {
    contacts,
    hasConditions,
    externalSearching,
    externalSearchNext,
    internalSearching,
    internalSearchNext,
    searchExternal,
  } = useSearchedContacts(type, { keyword, externalTags, groupTags })

  const onChooseContact = useCallback(
    (contact: Contact) => {
      services.contacts.current.mark(contact)
      onClose()
    },
    [onClose],
  )

  const [showingHistorySearch, showHistorySearch, hideHistorySearch] = useBoolean(false)
  const historySearchFinish = useCallback(
    (switchedId?: string) => {
      if (switchedId !== undefined) {
        const contact = services.contacts.getById(switchedId)
        if (contact) {
          services.contacts.current.mark(switchedId)
        }
        hideHistorySearch()
        onClose()
      } else {
        hideHistorySearch()
      }
    },
    [hideHistorySearch, onClose],
  )

  const [showingFullSearch, showFullSearch, hideFullSearch] = useBoolean(false)
  const fullSearchFinish = useCallback(
    (hasChoosed: boolean) => {
      hideFullSearch()
      if (hasChoosed) onClose()
    },
    [hideFullSearch, onClose],
  )

  const canFullSearch =
    account?.isAdmin === true || account?.permissions.includes(Permission.AnyTransfer) === true

  const [openMobileApply, setOpenMobileApply] = useState('')

  const inputRef = useRef<InputRef>(null)
  useEffect(() => inputRef.current?.focus(), [])

  return <div styleName="modal">
    <header>
      <Input
        prefix={<SearchOutlined />}
        placeholder="搜索联系人/群/聊天记录"
        value={keyword}
        onChange={e => setKeyword(e.target.value)}
        ref={inputRef}
      />

      {type === ContactType.external ? (
        <ChooseExternalTags choosed={externalTags} onChoosed={setExternalTags} />
      ) : null}
      {type === ContactType.group ? (
        <ChooseGroupTags choosed={groupTags} onChoosed={setGroupTags} />
      ) : null}
    </header>

    {externalTags ? (
      <ChoosedExternalTags
        visible={type === ContactType.external}
        choosed={externalTags}
        onUpdated={setExternalTags}
        onRefresh={searchExternal}
      />
    ) : null}
    {groupTags ? (
      <ChoosedGroupTags
        visible={type === ContactType.group}
        choosed={groupTags}
        onUpdated={setGroupTags}
      />
    ) : null}

    {keyword ? (
      <div styleName="extra-search" onClick={showHistorySearch}>
        <SearchOutlined />
        查看相关聊天记录
      </div>
    ) : null}
    <HistorySearch
      visible={showingHistorySearch}
      onClose={historySearchFinish}
      initialKeyword={keyword}
    />

    {type === ContactType.external && keyword && canFullSearch ? (
      <Actionable>
        <div styleName="extra-search" onClick={showFullSearch}>
          <UserOutlined />
          在全量客户中查找
        </div>
      </Actionable>
    ) : null}
    <FullSearch visible={showingFullSearch} onClose={fullSearchFinish} initialKeyword={keyword} />

    {qywxs.size && type === ContactType.external && keyword && /^\d+$/.exec(keyword) ? (
      <div styleName="extra-search" onClick={() => setOpenMobileApply(keyword)}>
        <MobileOutlined />
        手机号加人
      </div>
    ) : null}
    <MobileApply
      open={openMobileApply !== ''}
      initialMobile={openMobileApply}
      onClose={(joined: boolean) => {
        setOpenMobileApply('')
        if (joined) onClose()
      }}
    />

    <Categories current={type} setCurrent={setType} />

    <ContactList
      type={type}
      onClick={onChooseContact}
      hasConditions={hasConditions}
      contacts={contacts}
      externalSearching={externalSearching}
      externalSearchNext={externalSearchNext}
      internalSearching={internalSearching}
      internalSearchNext={internalSearchNext}
    />
  </div>
}
